
Ext.ns('App');

App.initMain = function() {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    Ext.Msg.minWidth = 300;

    App.createViewport();

    setTimeout(function() {
      Ext.get('loading').remove();
      Ext.get('loading-mask').fadeOut({ remove: true });
    }, 250);
    
    // 处理用户发送ajax请求超时和用户登陆失效
    Ext.Ajax.on('requestcomplete',checkUserSessionStatus, this); 
    function checkUserSessionStatus(conn,response,options){   
        if(response.getResponseHeader("sessionstatus") == "timeout"){
        	Ext.Msg.alert('登陆过期','由于您长时间未操作,登录已超时，请重新登陆!',
    	                function(btn) {
	                    	window.location = 'index.jsp';
    	                 }
        	);
        }  
    }
    //请求超过30s
    Ext.Ajax.on('requestexception',requestTimeout, this); 
    function requestTimeout(conn,response,options){   
        if(response.status == -1){
        	Ext.Msg.alert('请求超时','可能是因为网络原因,请求超时,点击确定刷新页面!',
	                function(btn) {
        				window.location.reload; 
	                 }
        	);
        }    
    }
    
};

Ext.onReady(App.initMain);

App.createViewport = function() {
    var viewport = new Ext.Viewport({
        layout: 'border',
        items: [
            App.createNorth(),
            App.createWest(),
            App.createCenter()
        ]
    });
};

App.createNorth = function() {
    return ({
        region: 'north',
        title:'<div align="center"><b style="font-size:12px; left:50%;">欢迎您，<font color=red>'+loginUserName+'</font></b></div>',
    	width: window.screenTop,
    	bodyStyle:'margin-top:0px; left: 0px; top: 0px; height: 0px; display: none; visibility: collapse; position: static; z-index: auto;',
    	hideCollapseTool: false,
    	titleCollapse: true,
    	collapsible: true,
    	collapsed: true,
        tbar: [
               new Ext.form.ComboBox({
                   store: new Ext.data.ArrayStore({
                       fields: ['title', 'name'],
                       data :  [
                                ['blue', '蓝色主题'],
                                ['gray', '灰色主题']
                               ]
                   }),
                   displayField:'name',
                   valueField:'title',
                   id:'styleswitcher_select',
                   typeAhead: true,
                   editable:false,
                   mode: 'local',
                   forceSelection: true,
                   triggerAction: 'all',
                   emptyText:'选择主题...',
                   selectOnFocus:true,
                   listeners: {
            	   		select : function(){
            	   		   if(this.getValue()==''){
            	   			   return;
            	   		   };
                           setActiveStyleSheet(this.getValue());
                       },
                       afterrender :function(){
                    	   var cookie = readCookie("style");
                           var title = cookie ? cookie : getPreferredStyleSheet();
                          this.setValue(title);
                       }
                   }
               }),
            '->', {
            text: '修改密码',
            scope: this,
            handler: function() {
                if (App.ChangePasswordDialog) {
                    App.ChangePasswordDialog.show();
                }
            }
        }, {
            text: '退出',
            scope: this,
            handler: function() {
                window.location = 'quit.jsp';
                window.close();
            }
        }]
   
    });
};

App.createWest = function() {
	Ext.Ajax.request({
		method:'post',
		url:'user/menus',
		success: function(resp, opts) {
	        var result = Ext.util.JSON.decode(resp.responseText);
	        if(result.success=='true') {
	            for (var i = 0; i < result.data.length; i++) {
					var item = result.data[i];
					var title = "<div style='background:url(" + item.image
						+ ") no-repeat;padding-left:20px;'>" + item.name + "</div>";
					for (var j = 0; j < item.children.length; j++) {
						var o = item.children[j];
						o.text = o.name;
						o.icon = o.image;
					}
					var node = new Ext.tree.TreePanel({
						title: title,
						rootVisible: false,
						lines: false,
						autoScroll: true,
						qtips: item.qitps,
						root: {
							editable: false,
							expanded: true,
							text: item.name,
							draggable: false,
							children: item.children
						},
						listeners: {
							click: function(node, e) {
								App.mainPanel.openTab(node);
							}
						}
					});
					Ext.getCmp('mainMenu').add(node);
				}
				Ext.getCmp('mainMenu').doLayout();
	        }else {
	            Ext.Msg.alert('提示',respText.info);
	        }
	    },
	    failure: function(resp,opts) {
	        //系统请求出错
	        Ext.Msg.alert('提示', '系统请求错误！'); 
	    }
	});
    return {
        id: 'mainMenu',
        region: 'west',
        layout: 'accordion',
        title: '功能菜单',
        split: true,
        width: 150,
        minSize: 100,
        maxSize: 400,
        collapsible: true,
        margin: '0 0 5 5',
        cmargins: '0 5 5 5',
        lines: false,
        autoScroll: true
    };
};

App.createCenter = function() {
    var noticesore=new Ext.data.Store({
    	autoLoad:true,
		baseParams:{start:0, limit:5},
		proxy: new Ext.data.HttpProxy({
			url : 'notice/noticelist'
		}),
        remoteSort: false,
		reader: new Ext.data.JsonReader({
			totalProperty : 'totalCount',
			root : 'rows',
			idProperty : 'id',
			fields: [{
				name: 'id',
				type: 'string'
			},
			{
				name: 'title',
				type: 'string'
			},
			{
				name: 'name',
				type: 'string'
			},
			{
				name: 'create_date',
				type: 'date',
				dateFormat: 'time'
			},{
				name: 'modify_date',
				type: 'date',
				dateFormat: 'time'
			}]
		})/*,
		 listeners:{
    		scope: this,
    		load : function(store){
				this.mainPanel.find('grid')[1].getSelectionModel().selectFirstRow();
			}
		}*/
    });
    var mainPanel = new Ext.TabPanel({
        id: 'main-tabs',
        activeTab: 0,
        region: 'center',
        margins: '0 5 5 0',
        resizeTabs: true,
        tabWidth: 150,
        minTabWidth: 120,
        enableTabScroll: true,
        items: [{
            id: 'main-view',
            layout: 'fit',
            title: '欢迎您',
            closable: false,
            hideMode: 'offsets',
            autoScroll: true,
            items:[{
            		xtype:'grid',
            		ref:'homenoitce',
                	tbar: new Ext.PagingToolbar({
                		pageSize: 5 ,//分页必须加的参数.最好和store里面的limit保持一致
                        displayInfo: true//,
//                        store:noticesore
                    }),
                    title:"<div align='center'>公&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;告(点击查看)</div>",//打印必须设置tile
                    viewConfig : {autoFill:false,forceFit:true},
                    autoHeight:true,
                    store: noticesore,
                    sm: new Ext.grid.RowSelectionModel({
                    	singleSelect:true,
                    	listeners:{
                    		rowselect : function(select){
		                    	var parentPanel = this.grid.findParentByType('panel');
		                		parentPanel.remove('panelHtml');
		            			var id = this.grid.getSelectionModel().getSelected().get('id');
		            			Ext.Ajax.request({
		                            waitMsg: '数据读取中',
		                            url: 'notice/getmessagebyid', //请求URL(JSP/Servlet)
		                            params: {id: id }, //设置传递参数
		                            success: function(resp, opts) {//成功后的回调方法
		                            	var respText = Ext.util.JSON.decode(resp.responseText); //解码JSON格式数据为一个对象
		                            	if(respText.success){
		                            		parentPanel.add(new Ext.Panel({id:'panelHtml',html:respText.rows}));
		                            		parentPanel.doLayout();
		                            	}else{
		                            		Ext.Msg.alert('提示',"该公告数据库没有记录,请删除" );
		                            	}
		                            },
		                            failure: function(resp, opts) {//失败 
		                                var respText = Ext.util.JSON.decode(resp.responseText);
		                                Ext.Msg.alert('网络错误', respText.error);
		                            }
		                        });
        					}
        				}
                    	}),
                    columns: [{
                        header: "标题",
                        width: 150,
                        sortable: true,
                        dataIndex: 'title',
                        renderer:this.highLight
                    },
                    {
                        header: "发布公告人",
                        width: 100,
                        sortable: true,
                        dataIndex: 'name',
                        renderer:this.highLight
                    },
                    {
                        header: "发布日期",
                        width: 100,
                        sortable: true,
                        dataIndex: 'create_date',
                        renderer: Ext.util.Format.dateRenderer('Y-m-d h:m:s')
                    },{
                    	header:'修改日期',
                    	 width: 100,
                         sortable: true,
                         dataIndex: 'modify_date',
                         renderer: Ext.util.Format.dateRenderer('Y-m-d h:m:s')
                    }]
            }]
        }]
    });
    mainPanel.openTab = function(node) {
        var id = node.attributes.url;
        var newTab = false;
        var tab = this.getItem(id);
        if (!tab) {
            tab = new Ext.Panel({
                id: id,
                title: node.text,
                tabTip: node.text,
                layout: 'fit',
                html: '<img alt="" src="scripts/ext-3.3.1/resources/images/default/shared/large-loading.gif" width="32" height="32" style="margin-right:8px;" align="absmiddle"/>正在加载...',
                closable: true,
                autoScroll: true,
                border: true
            });
            this.add(tab);
            newTab = true;
        }
        this.setActiveTab(tab);
        if(!newTab && App[tab.id] && App[tab.id].store){
        	App[tab.id].store.reload();//点击菜单重新加载数据
        }
        if (newTab) {
			if (App[id]) {
                App[id].render(id);
                this.doLayout();
            } else {
                Ext.Ajax.request({
                    panelId: id,
                    url: 'scripts/modules/' + id + '.js',
                    success: function(response, opts) {
                        var o = eval(response.responseText);
                        if (o) {
                            App[id].render(opts.panelId);
                            this.doLayout();
                        }
                    },
                    failure: function() {
                        Ext.Msg.alert("错误","加载模块失败！");
                    },
                    scope: this
                });
            }
        }
    };

    App.mainPanel = mainPanel;
    return mainPanel;
};
